
public class TicketThread implements Runnable{
    int ticket  = 100;
    Object obj = new Object();
    public void run() {
        //method(); //method是实现了同步方法，可以解决火车票出现的问题，
        while(true) {
            synchronized (obj) {  //也可以在run()里面采用同步代码块的形式，来解决出现的异常
                if(ticket>0) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + ":" + ticket--);
                }
            }
        }

    }
    private synchronized void method() {
        while(true) {
            if(ticket>0) {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName()+ ":" + ticket--);
            }
        }
    }

}

